﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using Microsoft.Devices;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using zxingwp7;
using zxingwp7.common;
using zxingwp7.oned;
using zxingwp7.qrcode;
using System.IO;

namespace WP_Customer_ShopMob.Views
{
    public partial class MainPage : PhoneApplicationPage
    {
        private PhotoCamera camera;
        private ViewModels.MainViewModel mvm;
        private Model.Repository repo = new Model.Repository();
        private readonly System.Windows.Threading.DispatcherTimer _timer;

        private PhotoCameraLuminanceSource _luminance;
        private zxingwp7.qrcode.QRCodeReader _reader;

        public MainPage()
        {
            InitializeComponent();
            _timer = new System.Windows.Threading.DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(250);
            _timer.Tick += (o, arg) => ScanPreviewBuffer();
        }

        private void alert(string p)
        {
            MessageBox.Show(p);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string login;
            if (NavigationContext.QueryString.TryGetValue("id", out login))
            {
                mvm = new ViewModels.MainViewModel();
                var cl = Helper.IsolatedStorage.Load<ViewModels.ClientViewModel>("compte");
                if (cl != null && cl.IdClient == login)
                {
                    mvm.Compte = cl;
                    var categs = Helper.IsolatedStorage.Load<ObservableCollection<ViewModels.CategorieViewModel>>("categories").Where(x => x.IdMere == 0);
                    foreach (var categ in categs)
                    {
                        mvm.ListCategories.Add(categ);
                    }
                }
                else
                {
                    mvm.LoadData(login);
                }
                this.DataContext = mvm;
            }
        }

        private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (lst_categories.SelectedItem == null) return;
            ViewModels.CategorieViewModel cvm = (lst_categories.SelectedItem as ViewModels.CategorieViewModel);
            if (!cvm.IsDataLoaded)
            {
                cvm.LoadData(NavigationService);
            }
            //while (!cvm.IsDataLoaded) { }
            //var categs = Helper.IsolatedStorage.Load<ObservableCollection<ViewModels.CategorieViewModel>>("categories").Where(x => x.IdMere == cvm.Id).Count();
            //var arts = Helper.IsolatedStorage.Load<ObservableCollection<ViewModels.ArticleViewModel>>("articles");
            //if (categs != 0)
            //{
            //    NavigationService.Navigate(new Uri("/Views/sousCategoriesPage.xaml?id=" + cvm.Id, UriKind.Relative));
            //}
            //else if (arts != null && arts.Where(x => x.IdCategorie == cvm.Id).Count() != 0)
            //{
            //    NavigationService.Navigate(new Uri("/Views/CategoriesPage.xaml?id=" + cvm.Id, UriKind.Relative));
            //}
            //else
            //{
            //    alert("Aucun contenu disponible");
            //}
            
            lst_categories.SelectedItem = null;
        }

        private void txt_search_TextChanged(object sender, TextChangedEventArgs e)
        {
            mvm.Search = txt_search.Text;
        }

        private void btn_deconnexion_Click_1(object sender, EventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings.Remove("login");
            NavigationService.Navigate(new Uri("/Views/LogPage.xaml", UriKind.Relative));
        }


        private void lst_search_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (lst_search == null) return;
            ViewModels.ArticleViewModel avm = (lst_search.SelectedItem as ViewModels.ArticleViewModel);
            NavigationService.Navigate(new Uri("/Views/ArticlesPage.xaml?id=" + avm.IdArticle, UriKind.Relative));
            lst_search = null;
        }

        private void Pivot_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (pivot.SelectedIndex == 2)
            {
                if (null == camera)
                {
                    camera = new PhotoCamera();

                    // déclenchement de la caméra à l'initialisation
                    camera.Initialized += camera_Initialised;
                    viewfinderBrush.SetSource(camera);
                    CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;

                    // réglage du motif capturé en sortie de la caméra
                    videoRotateTransform.CenterX = videoRectangle.Width / 2;
                    videoRotateTransform.CenterY = videoRectangle.Height / 2;
                    videoRotateTransform.Angle = 90;
                }
            }
        }

       #region Du code concernant lacaméra
        // user navigated away from page
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (camera != null)
            {
                // unhook the event handlers
                camera.Initialized -= camera_Initialised;

                // dispose of the camera object
                camera.Dispose();
            }

            base.OnNavigatedFrom(e);
        }


        private void ScanPreviewBuffer()
        {
            try
            {
                camera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);
                var binBitmap = new BinaryBitmap(binarizer);
                var result = _reader.decode(binBitmap);
                Dispatcher.BeginInvoke(() => repo.GetArticlesById(long.Parse(result.Text), delegate(string resu, Exception error)
                {
                    if (error != null)
                    {
                        if (!String.IsNullOrEmpty(resu))
                        {
                            NavigationService.Navigate(new Uri("/Views/ArticlesPage.xaml?id=" + result.Text, UriKind.Relative));
                        }
                    }
                    else
                        MessageBox.Show(error.Message);
                }));
            }
            catch
            {
            }
        }

        private void camera_Initialised(object sender, CameraOperationCompletedEventArgs e)
        {
            // on règle la résolution de la caméra
            if (e.Succeeded)
            {
                int width = Convert.ToInt32(camera.PreviewResolution.Width);
                int height = Convert.ToInt32(camera.PreviewResolution.Height);

                _luminance = new PhotoCameraLuminanceSource(width, height);
                _reader = new QRCodeReader();

                Dispatcher.BeginInvoke(() =>
                {
                    _timer.Start();
                });
            }
        }

        /*private void camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
        {
            
            capturing = false;

            Stream imageStream = (Stream)e.ImageStream;
            Result result;

            Dispatcher.BeginInvoke(() =>
            {

                WriteableBitmap qrImage = new WriteableBitmap((int)camera.Resolution.Width, (int)camera.Resolution.Height);
                imageStream.Position = 0;
                qrImage.LoadJpeg(imageStream);
                var multireader = new MultiFormatReader();
                var formats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE, BarcodeFormat.EAN_13 };
                var hints = new Dictionary<DecodeHintType, Object>();
                hints.Add(DecodeHintType.POSSIBLE_FORMATS, formats);
                multireader.Hints = hints;
                /*
                 * multireader.decodeWithState(qrImage);
                possibleFormats.Add(BarcodeFormat.QR_CODE);

                decodingOptions.Add(DecodeHintType.POSSIBLE_FORMATS, possibleFormats);
                */
                /*try
                {
                    //result = barcodeDecoder.Decode(qrImage);

                    //resultText.Text = result.Text;
                }
                
                catch (Exception ex)
                {
                    // something else went wrong, so alert the user
                    MessageBox.Show(ex.Message, "Erreur lors du déchiffrage du QR code", MessageBoxButton.OK);
                }
            });
        }*/
            
        
        void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e)
        {
            if (camera.IsFocusSupported)
            {
                camera.Focus();
            }
        }
        #endregion


    }
}